package com.tonghe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tonghe.constants.SystemConstants;
import com.tonghe.domain.ResponseResult;
import com.tonghe.domain.dto.ArticleDto;
import com.tonghe.domain.dto.QueryArticleDTO;
import com.tonghe.domain.entity.Article;
import com.tonghe.domain.entity.ArticleTag;
import com.tonghe.domain.entity.Category;
import com.tonghe.enums.AppHttpCodeEnum;
import com.tonghe.mapper.ArticleMapper;
import com.tonghe.service.ArticleService;
import com.tonghe.service.ArticleTagService;
import com.tonghe.service.CategoryService;
import com.tonghe.service.RoleService;
import com.tonghe.utils.BeanCopyUtils;
import com.tonghe.utils.RedisCache;
import com.tonghe.utils.SecurityUtils;
import com.tonghe.vo.ArticleDetailVo;
import com.tonghe.vo.ArticleListVo;
import com.tonghe.vo.HotArticleVo;
import com.tonghe.vo.PageVo;
import com.tonghe.vo.sys.AddArticleDto;
import com.tonghe.vo.sys.ArticleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Date:2022/2/14- 02- 14- 19:35
 * @author: tonghe
 **/
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ArticleTagService articleTagService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private RedisCache redisCache;

    /**
    * @description: 查询热门文章
    * @author: TongHe
    * @date: 2022/3/17 17:55
    */
    @Override
    public ResponseResult hotArticleList() {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        queryWrapper.orderByDesc(Article::getViewCount);
        Page<Article> page = new Page(1,10);

        page(page,queryWrapper);
        List<Article> articles = page.getRecords();

        List<HotArticleVo> articleVos = BeanCopyUtils.copyBeanList(articles, HotArticleVo.class);
        return ResponseResult.okResult(articleVos);
    }

    /**
    * @description: 前台 文章列表
    * @param： [pageNum, pageSize, categoryId]
    * @author: TongHe
    * @date: 2022/3/17 17:55
    */
    @Override
    public ResponseResult articleList(Integer pageNum, Integer pageSize, Long categoryId) {

        LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Objects.nonNull(categoryId) && categoryId > 0, Article::getCategoryId, categoryId);
        lambdaQueryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        lambdaQueryWrapper.orderByDesc(Article::getIsTop);

        Page<Article> page = new Page<>(pageNum, pageSize);
        page(page, lambdaQueryWrapper);
        List<Article> articles = page.getRecords();

        articles.stream()
                .map(article -> article.setCategoryName(categoryService.getById(article.getCategoryId()).getName()))
                .collect(Collectors.toList());

        List<ArticleListVo> articleListVos = BeanCopyUtils.copyBeanList(page.getRecords(), ArticleListVo.class);
        PageVo pageVo = new PageVo(articleListVos, page.getTotal());

        return ResponseResult.okResult(pageVo);
    }

    // TODO es
    @Override
    public ResponseResult articleList(Integer pageNum, Integer pageSize, QueryArticleDTO queryArticleDTO) {
        /*
         * 查询条件
         * 1. 如果categoryId（分类Id）为空或者不为空
         * 2、状态是正常发布的
         * 3. 置顶文章（istop）排在前面
         * */
        LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // TODO 全模糊？
        lambdaQueryWrapper.like(Objects.nonNull(queryArticleDTO.getSummary()), Article::getSummary, queryArticleDTO.getSummary());
        lambdaQueryWrapper.like(Objects.nonNull(queryArticleDTO.getTitle()), Article::getTitle, queryArticleDTO.getTitle());
        lambdaQueryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        lambdaQueryWrapper.orderByDesc(Article::getIsTop);
        // TODO 如果角色是nor 则可以管理自己的文章
//        if(SecurityUtils.getLoginUser().getUser().getRoleIds())
        Long userId = SecurityUtils.getUserId();
        List<String> roleKeyList = roleService.selectRoleKeyByUserId(userId);
        if(roleKeyList.contains("nor"))        {
            lambdaQueryWrapper.eq(Article::getCreateBy,userId);
        }
        Page<Article> page = new Page<>(pageNum, pageSize);
        page(page, lambdaQueryWrapper);
        List<Article> articles = page.getRecords();
        articles.stream()
                .map(article -> article.setCategoryName(categoryService.getById(article.getCategoryId()).getName()))
                .collect(Collectors.toList());

        List<ArticleListVo> articleListVos = BeanCopyUtils.copyBeanList(page.getRecords(), ArticleListVo.class);

        PageVo pageVo = new PageVo(articleListVos, page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    /**
    * @description: 根据 文章id 获取文章详情
    * @param： [id]
    * @author: TongHe
    * @date: 2022/3/17 17:55
    */
    @Override
    public ResponseResult getArticleDetail(long id) {

        // 根据Id查询文章
        Article article = getById(id);

        if(article == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NOT_EXIST);
        }

        ArticleDetailVo articleDetailVo = BeanCopyUtils.copyBean(article, ArticleDetailVo.class);
        Category category = categoryService.getById(articleDetailVo.getCategoryId());
        if(category != null){
            articleDetailVo.setCategoryName(category.getName());
        }
        return ResponseResult.okResult(articleDetailVo);
    }

    /**
    * @description: 更改文章浏览量
    * @param： [id]
    * @author: TongHe
    * @date: 2022/5/9 15:25
    */
    @Override
    public ResponseResult updateViewCount(Long id) {

        // 调用redisCache更新redis中对应的id的浏览量
        redisCache.incrementCacheMapValue(SystemConstants.REDIS_VIEW_COUNT, id.toString(), 1);
        return null;
    }

    @Override
    @Transactional
    public ResponseResult add(AddArticleDto articleDto) {

        Article article = BeanCopyUtils.copyBean(articleDto, Article.class);
        article.setCreateBy(SecurityUtils.getUserId());
        article.setCreateTime(new Date());
        save(article);


        List<ArticleTag> articleTags = articleDto.getTags().stream()
                .map(tagId -> new ArticleTag(article.getId(), tagId))
                .collect(Collectors.toList());

        //添加 博客和标签的关联
        articleTagService.saveBatch(articleTags);
        return ResponseResult.okResult();
    }

    @Override
    public ArticleVo getInfo(Long id) {
        Article article = getById(id);
        //获取关联标签
        LambdaQueryWrapper<ArticleTag> articleTagLambdaQueryWrapper = new LambdaQueryWrapper<>();
        articleTagLambdaQueryWrapper.eq(ArticleTag::getArticleId,article.getId());
        List<ArticleTag> articleTags = articleTagService.list(articleTagLambdaQueryWrapper);
        List<Long> tags = articleTags.stream().map(articleTag -> articleTag.getTagId()).collect(Collectors.toList());

        ArticleVo articleVo = BeanCopyUtils.copyBean(article,ArticleVo.class);
        articleVo.setTags(tags);
        return articleVo;
    }

    @Override
    public void edit(ArticleDto articleDto) {
        Article article = BeanCopyUtils.copyBean(articleDto, Article.class);
        article.setUpdateBy(SecurityUtils.getUserId());
        article.setUpdateTime(new Date());
        //更新博客信息
        updateById(article);
        //删除原有的 标签和博客的关联
        LambdaQueryWrapper<ArticleTag> articleTagLambdaQueryWrapper = new LambdaQueryWrapper<>();
        articleTagLambdaQueryWrapper.eq(ArticleTag::getArticleId,article.getId());
        articleTagService.remove(articleTagLambdaQueryWrapper);
        //添加新的博客和标签的关联信息
        List<ArticleTag> articleTags = articleDto.getTags().stream()
                .map(tagId -> new ArticleTag(articleDto.getId(), tagId))
                .collect(Collectors.toList());
        articleTagService.saveBatch(articleTags);
    }
}
